package org.rescue.search;

import com.google.soap.search.*;
import java.util.ArrayList;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;

public class SearchGoogle implements SearchBehavior {

	String googleKey;
	
	public SearchGoogle()
	throws SearchException {
		try {		
			Configuration config = new PropertiesConfiguration("diamond.properties");			
			googleKey = config.getString("google.key");
		}
		catch (ConfigurationException ce) {
			throw new SearchException("Error opening diamond.properties configuration file:", ce.getMessage());
		}
	}
	
	
	/**
	 * search() connects to the Google webservice, executes the search, 
	 * and creates a SearchDocument in the dataset for each result.
	 */
	public ArrayList<Document> search(String query, int numResults)
	throws SearchException {

		ArrayList<Document> hits = new ArrayList<Document>();
		int cnt = 0;
		
		// Google API has maximum of 10 hits per request, so must separate
		// into multiple calls to get > 10 results.
		
		for (int i = 0; i<Math.ceil((double)numResults / 10.0); i++ ) {
		
			try {
				GoogleSearch s = new GoogleSearch();
				s.setKey(googleKey);
				s.setQueryString(query);
				s.setMaxResults(10);
				s.setStartResult(i*10);
				
				GoogleSearchResult r = s.doSearch();
					
				if (r.getEstimatedTotalResultsCount() > 0) {
					GoogleSearchResultElement[] results = r.getResultElements();
					for (GoogleSearchResultElement e : results) {
						Document d = new Document();
						d.setTitle(e.getTitle());
						d.setURL(e.getURL());
						cnt++;
						// save page content 
						//byte [] cachedBytes = s.doGetCachedPage(e.getURL());
				        //d.setContents(new String(cachedBytes));				
				        if (cnt <= numResults){
				        	hits.add(d);		
				        }
					}
				}
			} 
			catch (GoogleSearchFault f) {	      	
		      	throw new SearchException("Google Web API call failed.", f.toString());
			}
			
		}
		
		return hits;
	}		
	
}


